<script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import type {
  BalanceAlarm,
  BalanceAlarmQueryRequest,
  BalanceAlarmVO,
} from "@/models/balanceAlarm";
import {
  listBalanceAlarmByPage,
  addBalanceAlarm,
  updateBalanceAlarm,
  deleteBalanceAlarm,
  listBalanceAlarmByPageVo,
} from "@/api/balanceAlarm";
import dayjs from "dayjs";
import { getCurrentUser } from "@/api/user";
import { UserVO } from "@/models/user";

const userInfo = ref<UserVO>();

// 表格数据
const dataSource = ref<BalanceAlarmVO[]>([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(6);
// 搜索条件
const searchForm = ref({
  dormitoryId: undefined,
  equipmentId: undefined,
  isSolved: undefined,
  dateRange: [],
});

const isAdd = ref(false);

// 获取用户信息并初始化查询
const getUserInfo = async () => {
  try {
    const res = await getCurrentUser();
    if (res.data.code === 0) {
      userInfo.value = res.data.data;
      // 更新 searchForm 中的 dormitoryId
      searchForm.value.dormitoryId = userInfo.value?.dormitoryId;
      // 获取用户信息后再调用查询
      await fetchRecords();
    }
  } catch (error) {
    message.error("获取用户信息失败");
  }
};

// 获取数据列表
const fetchRecords = async () => {
  loading.value = true;
  try {
    const queryRequest: BalanceAlarmQueryRequest = {
      current: currentPage.value,
      pageSize: pageSize.value,
      dormitoryId: searchForm.value.dormitoryId, // 使用 searchForm 中的值
      equipmentId: searchForm.value.equipmentId,
      isSolved: searchForm.value.isSolved,
      startDate: searchForm.value.dateRange?.[0]
        ? dayjs(searchForm.value.dateRange[0]).format("YYYY-MM-DD")
        : undefined,
      endDate: searchForm.value.dateRange?.[1]
        ? dayjs(searchForm.value.dateRange[1]).format("YYYY-MM-DD")
        : undefined,
    };

    const res = await listBalanceAlarmByPageVo(queryRequest);
    if (res.data.code === 0) {
      dataSource.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      message.error("获取数据失败");
    }
  } catch (error) {
    message.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 处理表格变化
const handleTableChange = (pagination: any) => {
  currentPage.value = pagination.current;
  pageSize.value = pagination.pageSize;
  fetchRecords();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchRecords();
};

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    dormitoryId: userInfo.value?.dormitoryId,
    equipmentId: undefined,
    isSolved: undefined,
    dateRange: [],
  };
  currentPage.value = 1;
  fetchRecords();
};

onMounted(() => {
  getUserInfo(); // 只调用 getUserInfo，fetchRecords 会在获取用户信息后自动调用
});
</script>

<template>
  <div class="page-container">
    <div class="balance-alarm-management">
      <!-- 搜索表单 -->
      <a-card class="search-card">
        <a-form layout="inline">
          <a-form-item label="处理状态">
            <a-select
              v-model:value="searchForm.isSolved"
              placeholder="请选择状态"
              allowClear
            >
              <a-select-option :value="0">未处理</a-select-option>
              <a-select-option :value="1">已处理</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="报警日期">
            <a-range-picker
              v-model:value="searchForm.dateRange"
              :placeholder="['开始日期', '结束日期']"
              style="width: 240px"
            />
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleSearch">搜索</a-button>
              <a-button @click="handleReset">重置</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 数据表格 -->
      <a-card class="table-card">
        <a-table
          :dataSource="dataSource"
          :loading="loading"
          :pagination="{
            total,
            current: currentPage,
            pageSize,
            showSizeChanger: true,
            showQuickJumper: true,
          }"
          @change="handleTableChange"
        >
          <a-table-column title="设备类型">
            <template #default="{ record }">
              <a-tag
                :color="
                  record.equipmentInfo?.typeName == '1' ? 'blue' : 'green'
                "
              >
                {{ record.equipmentInfo?.typeName == "1" ? "水表" : "电表" }}
              </a-tag>
            </template>
          </a-table-column>

          <a-table-column title="设备余额" dataIndex="deviceBalance" />
          <a-table-column title="处理状态" dataIndex="isSolved">
            <template #default="{ text }">
              <a-tag :color="text === 1 ? 'green' : 'red'">
                {{ text === 1 ? "已处理" : "未处理" }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="备注" dataIndex="note" />
          <a-table-column
            title="报警日期"
            dataIndex="alarmDate"
            :customRender="
              ({ text }) => (text ? dayjs(text).format('YYYY-MM-DD') : '-')
            "
          />
          <a-table-column
            title="创建时间"
            dataIndex="createTime"
            :customRender="
              ({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
            "
          />
        </a-table>
      </a-card>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  height: calc(100vh - 64px); /* 减去顶部导航栏的高度 */
  overflow-y: auto;
  background-color: #f0f2f5;
}

.balance-alarm-management {
  padding: 24px;
}

.search-card {
  margin-bottom: 24px;
}

.table-card {
  background: #fff;
}

:deep(.ant-card-body) {
  padding: 24px;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}
</style>
